package cn.edik.plugin.dubbo.core;

import cn.edik.plugin.dubbo.annotation.Reference;
import com.jfinal.core.Controller;
import com.jfinal.core.ControllerFactory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ReferenceAutowiredControllerFactory extends ControllerFactory {

    private ThreadLocal<Map<Class<? extends Controller>, Controller>> buffers = new ThreadLocal<Map<Class<? extends Controller>, Controller>>() {
        protected Map<Class<? extends Controller>, Controller> initialValue() {
            return new HashMap<Class<? extends Controller>, Controller>();
        }
    };

    @Override
    public Controller getController(Class<? extends Controller> controllerClass) throws InstantiationException, IllegalAccessException {
        Controller ret = buffers.get().get(controllerClass);
        if (ret == null) {
            ret = controllerClass.newInstance();
            inject(ret);
            buffers.get().put(controllerClass, ret);
        }
        return ret;
    }

    private void inject(Controller ret) throws IllegalAccessException {
        Field[] fields = ret.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Reference.class)) {
                Reference reference = field.getAnnotation(Reference.class);
                Map<String, String> config = JFinalDubbo.buildPara(reference);
                field.setAccessible(true);
                field.set(ret, JFinalDubbo.receiveService(field.getType(), config));
            }
        }
    }

}
